package bai.publicwelfare_backend.service.impl.activity;

import bai.publicwelfare_backend.common.utils.JwtUtil;
import bai.publicwelfare_backend.exception.BusinessException;
import bai.publicwelfare_backend.exception.ErrorCode;
import bai.publicwelfare_backend.mapper.activity.ActivityMapper;
import bai.publicwelfare_backend.mapper.user.UserMapper;
import bai.publicwelfare_backend.pojo.dto.activity.CharityEventDTO;
import bai.publicwelfare_backend.pojo.dto.activity.EventParticipantDTO;
import bai.publicwelfare_backend.pojo.dto.user.BadgeUser;
import bai.publicwelfare_backend.pojo.entity.activity.Badge;
import bai.publicwelfare_backend.pojo.entity.activity.CharityEvent;
import bai.publicwelfare_backend.pojo.entity.activity.EventParticipant;
import bai.publicwelfare_backend.pojo.entity.activity.UserBadge;
import bai.publicwelfare_backend.pojo.entity.user.User;
import bai.publicwelfare_backend.service.activity.ActivityServiceI;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
public class ActivityService implements ActivityServiceI {
    private final JwtUtil jwtUtil;
    @Autowired ActivityMapper activityMapper;
    @Autowired UserMapper userMapper;
    @Override
    public void release(CharityEventDTO dto, HttpServletRequest request) {
        // 创建新活动
        CharityEvent charityEvent = new CharityEvent();
        BeanUtils.copyProperties(dto, charityEvent);
        // 设置组织者ID
        String token = request.getHeader("Authorization");
        Long userId = jwtUtil.getUserIdFromToken(token);
        charityEvent.setOrganizerId(userId);

        // 设置创建时间为当前时间
        charityEvent.setCreatedAt(LocalDateTime.now());

        // 设置默认状态
        charityEvent.setStatus(1); // '活动状态：0-已取消，1-正常，2-已结束'



        activityMapper.release(charityEvent);

    }

    @Transactional
    @Override
    public void attend(EventParticipantDTO dto, HttpServletRequest request) {

        // 设置组织者ID
        String token = request.getHeader("Authorization");
        Long userId = jwtUtil.getUserIdFromToken(token);

        // 校验活动有效性
        CharityEvent event = activityMapper.selectEventById(dto.getEventId());
        if (event == null) {
            throw new BusinessException(ErrorCode.EVENT_NOT_FOUND);
        }
        if (event.getStatus() != 1) {
            throw new BusinessException(ErrorCode.EVENT_STATUS_INVALID);
        }

        if (event.getActualParticipants() >= event.getMaxParticipants()) {
            throw new BusinessException(ErrorCode.PARTICIPATION_LIMIT);
        }

        // 检查是否已参与
        if (activityMapper.isParticipated(dto.getEventId(), userId)) {
            throw new BusinessException(ErrorCode.PARTICIPATION_DUPLICATE);
        }
        // 参加新活动
        EventParticipant eventParticipant = new EventParticipant();
        BeanUtils.copyProperties(dto, eventParticipant);
        eventParticipant.setUserId(userId);
        eventParticipant.setJoinedAt(LocalDateTime.now());

//        插入参与者记录
        activityMapper.attend(eventParticipant);
//        更新活动的实际参与人数
        activityMapper.incrementActualParticipants(dto.getEventId());
    }

    @Override
    public PageInfo<CharityEvent> obtain(int pageNum, int pageSize) {
        // 设置分页参数
        PageHelper.startPage(pageNum, pageSize);
        // 紧跟着的第一个查询会被分页
        List<CharityEvent> events = activityMapper.selectAllEvents();
        // 封装分页结果
        return new PageInfo<>(events);
    }

    @Override
    @Transactional
    public boolean RedeemBadge(BadgeUser badgeUser) {
        Long userId = badgeUser.getId();
        Integer badgeId = badgeUser.getBadgeId();
        User user = userMapper.selectById(userId);
        Badge badge = activityMapper.selectBadge(badgeId);
        List<UserBadge> userBadges = activityMapper.selectUserBadge(userId);

//        如果积分不足
        if (user.getPoints() < badge.getPointsRequired()) {
        throw new BusinessException(ErrorCode.POINTS_NOT_ENOUGH);
        }
        // 检查用户是否已经拥有该勋章
        boolean alreadyHasBadge = userBadges.stream()
                .anyMatch(ub -> ub.getBadgeId().equals(badgeId));

        if (alreadyHasBadge) {
            throw new BusinessException(ErrorCode.BADGE_ALREADY_OWNED);
        }

        // 3. 执行兑换操作（事务内）
        activityMapper.deductUserPoints(userId, badge.getPointsRequired());
        activityMapper.addUserBadge(userId, badgeId);

        return true;

    }

    @Override
    public List<UserBadge> QueryBadge(Long id) {
        return activityMapper.selectUserBadge(id);
    }

}


